package org.example.gochannel;

public abstract class TimeChannelWrapper extends ChannelExecWrapper<Integer> {
    private volatile boolean done = false;
    private volatile long waitTime = 0;

    public TimeChannelWrapper(JavaGoChannel<Integer> channel, long millsec) {
        super(channel);
        done = false;
        waitTime = millsec;
        initTimer();
    }

    private void initTimer() {
        Object timerObj = this;
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                for (; ; ) {
                    if (!done) {
                        done = true;
                        try {
                            Thread.sleep(waitTime);
                            if (!done) continue;// 计时器再次被重置
                            channel.out(0);
                            channel.in(0);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    } else {
                        Thread.yield();
                    }
                }
            }
        });
        t.setDaemon(true);
        t.start();
    }

    public synchronized void resetTimer(long millsec) {
        waitTime = millsec;
        done = false; // 注意先后顺序
    }
}
